package com.xhj.bigfactory.bootredis01;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
 * -
 *
 * @author 见见 pure_xhj@163.com @Date 2021-08-28 @Time 16:50
 */
@RestController
@RequestMapping("")
public class GoodsController {

  @Autowired private StringRedisTemplate stringRedisTemplate;

  @Value("${server.port}")
  private String serverPort;

  @GetMapping("/buy_goods")
  public String buy_goods() {
    String result = stringRedisTemplate.opsForValue().get("goods:001");
    int goodsNumber = result == null ? 0 : Integer.parseInt(result);

    if (goodsNumber > 0) {
      int realNumber = goodsNumber - 1;
      stringRedisTemplate.opsForValue().set("goods:001", String.valueOf(realNumber));
      System.out.println("成功买到商品, 库存还剩下:" + realNumber + "件\t服务端口:" + serverPort);

      return "成功买到商品, 库存还剩下:" + realNumber + "件 \t服务端口:" + serverPort;
    } else {
      System.out.println("商品已售完/活动结束/调用超时 \t服务端口:" + serverPort);
    }
    return "商品已售完/活动结束/调用超时 \t服务端口:" + serverPort;
  }
}
